clear
clear all
cap log close

log using "log-files/3_Table_B1.smcl", replace smcl

timer on 2

*-----------*
* Table B.1 *
*-----------*
	* Master data
	use "data/outputs/computo_ulttranstrepdate_missingsatmunmedian.dta", clear

	global educ "ed_prim ed_sec analfabetismo"

	drop if Pais != "Bolivia"

	* Trimming
	cumul trep_date_ulttrans, gen(cum_date)
	drop if cum_date <= 0.02 | cum_date >= 0.98
	drop cum_date
		
	* Margin
	gen mmargin_nbnn_so = mshare_nbnn_so - cshare_nbnn_so

	* Without this, Stata can't calculate the right ROT bandwidth
	su trep_date_ulttrans, d
	local global_mean = r(mean)
	local global_sd = r(sd)
	gen trep_date_ulttrans_norm = (trep_date_ulttrans - `global_mean') / `global_sd'

	egen muni_id = group(Pais Dep Prov Muni)

	* No controls
	reg mmargin_nbnn_so trep_date_ulttrans_norm, cluster(muni_id)
	outreg2 using "outputs/generated/Table_B1.tex", ///
		replace tex(frag) bdec(3) keep(trep_date_ulttrans_norm) nocon label noaster

	* + Lowlands
	reg mmargin_nbnn_so trep_date_ulttrans_norm medialuna, cluster(muni_id)
	outreg2 using "outputs/generated/Table_B1.tex", ///
		append tex(frag) bdec(3) keep(trep_date_ulttrans_norm) nocon label noaster

	* + Rural + education
	reg mmargin_nbnn_so trep_date_ulttrans_norm medialuna ln_density ///
		ln_aglabor logpop ln_dist_capital $educ, cluster(muni_id)
	outreg2 using "outputs/generated/Table_B1.tex", ///
		append tex(frag) bdec(3) keep(trep_date_ulttrans_norm) nocon label noaster

	* + 2016 MAS vote margin
	reg mmargin_nbnn_so trep_date_ulttrans_norm medialuna ln_density ///
		ln_aglabor logpop ln_dist_capital $educ margin2016, cluster(muni_id)
	outreg2 using "outputs/generated/Table_B1.tex", ///
		append tex(frag) bdec(3) keep(trep_date_ulttrans_norm) nocon label noaster

	* + 2016 MAS vote margin interacted with region dummys
	quietly tab Dep, gen(dum_dep)
	forvalues k = 1/9 {
		gen dum_dep`k'_margin = dum_dep`k' * margin2016
	}

	reg mmargin_nbnn_so trep_date_ulttrans_norm medialuna ln_density ln_aglabor logpop ///
		ln_dist_capital $educ margin2016 dum_dep*, cluster(muni_id)
	outreg2 using "outputs/generated/Table_B1.tex", ///
		append tex(frag) bdec(3) keep(trep_date_ulttrans_norm) nocon label noaster
	
	* Formatting	
	erase "outputs/generated/Table_B1.txt"

	insheet using "outputs/generated/Table_B1.tex", clear 

	keep if _n >= 5 & _n <= 9

	replace v1 = subinstr(v1,"\hline","",.)
	replace v1 = "\midrule" if v1 == "&  &  &  &  &  \\"

	replace v1 = subinstr(v1,"trep\_date\_ulttrans\_norm","Transmission Time",.)

	compress
	outsheet using "outputs/generated/Table_B1.tex", replace noname noquote nolabel

*------------------------------------------------------------------------------*
timer off 2
timer list 2

log close
clear all
